var WEB_ROOT = '/';
var ajaxSuccess = function(event, xhr, settings) {
    if (xhr && xhr.responseText) {
        try{
            var result = $.parseJSON(xhr.responseText);
            if (result && result.code == 102){
                sessionStorage.removeItem('user');
            }
            else if(result && result.code == 401)
            {
                if(top.msg) top.msg(result.msg);
                else
                    alert(result.msg);
            }
        }catch (e) {
            //加载html时会发生该错误，暂时不处理
        }
    }
}
$(document).ajaxSuccess(ajaxSuccess);

$(function()
{
    //加载所有与页面id同名的参数，值到value中
    var params = UrlParam.paramMap();
    for(var name in params)
    {
        var value = params[name].join();
        $('[id="' + name + '"]').val(value);
    }

})
//同步post
function globalSyncPost(url,params,successCallBack)
{
    globalPost(url,params,false,null,successCallBack);
}
//异步post
function globalAsyncPost(url,params,successCallBack)
{
    globalPost(url,params,true,null,function(result)
    {
        if(successCallBack) successCallBack(result);
    });
}

//异步postJson
function globalAsyncPostJson(url,params,successCallBack)
{
    globalPost(url,params,true,'application/json',successCallBack);
}

//post
function globalPost(url,params,async,contentType,successCallBack)
{
    var strParams = '';
    if(contentType == 'application/json') strParams = JSON.stringify(params);

    $.ajax({
        url: url,
        type: 'post',
        data: (strParams == ''?params:strParams),
        async:async,
        dataType: 'text',
        contentType: contentType || 'application/x-www-form-urlencoded',
        success : function(res) {
            try {
                var result =  $.parseJSON(res);
                if(result && (result.code == 102 || result.code == 401)) return;
                if(successCallBack) successCallBack(result);
            }
            catch(ex){console.log('系统响应错误');if(typeof console != 'undefined') console.log(ex); else alert(ex);}
        },
        error : function(error) {
            if(successCallBack) successCallBack({code:0,msg:'系统响应错误'});
            console.log('系统响应错误');
        }
    });
}
//加载表单信息
if (!Array.isArray) {
    Array.isArray = function(arg) {
        return Object.prototype.toString.call(arg) === '[object Array]';
    };
}
function loadFormData(data)
{
    if(!data) return;
    for ( var p in data) {
        if (data[p] && typeof (data[p]) == "object") {
            for ( var a in data[p]) {
                setDefaultValue(a,data[p][a]);
            }
        }else if(!Array.isArray(data[p])){
            setDefaultValue(p,data[p]);
        }
    }
}
function setDefaultValue(key,value)
{//按规则设置键值到表单中
    var hasValue = (value != undefined && value != null);
    var el = $("#" + key);//规则1：按id设置
    if(hasValue && el.length > 0) {
        if(el.is('input[type="text"]') || el.is('input[type="hidden"]') || el.is('input[type="hidden"]') || el.is('select') || el.is('textarea'))
            el[0].defaultValue = value;
        else if(!el.is('input[type="file"]'))
            el.text(value);
    }
    else {
        el = $('[name="' + key + '"]');//规则2：按name设置
        if(el.length > 0) {
            if(hasValue
                && (el.is('input[type="text"]')|| el.is('input[type="hidden"]') || el.is('select') || el.is('textarea')))
                el[0].defaultValue = value;
            else if(el.is('input[type="radio"]') || el.is('input[type="checkbox"]')) {
                el.filter('[value="' + value + '"]').prop('checked',true);
                el.filter('[value!="' + value + '"]').prop('checked',false);
                //默认值
                if(el.is('input[type="radio"]') && el.filter(':checked').length == 0)
                    el.eq(0).prop('checked',true);
            }
            else if(!el.is('input[type="file"]') && hasValue)
                el.text(value);
        }
    }
}

var UrlParam = function() { // url参数
    var data, index;
    (function init() {
        data = [];    //值，如[["1","2"],["zhangsan"],["lisi"]]
        index = {};   //键:索引，如{a:0,b:1,c:2}
        var u = window.location.search.substr(1);
        if (u != '') {
            var params = decodeURIComponent(u).split('&');
            for (var i = 0, len = params.length; i < len; i++) {
                if (params[i] != '') {
                    var p = params[i].split("=");
                    if (p.length == 1 || (p.length == 2 && p[1] == '')) {// p | p= | =
                        data.push(['']);
                        index[p[0]] = data.length - 1;
                    } else if (typeof(p[0]) == 'undefined' || p[0] == '') { // =c 舍弃
                        continue;
                    } else if (typeof(index[p[0]]) == 'undefined') { // c=aaa
                        data.push([p[1]]);
                        index[p[0]] = data.length - 1;
                    } else {// c=aaa
                        data[index[p[0]]].push(p[1]);
                    }
                }
            }
        }
    })();
    return {
        // 获得参数,类似request.getParameter()
        param : function(o) { // o: 参数名或者参数次序
            try {
                return (typeof(o) == 'number' ? data[o][0] : data[index[o]][0]);
            } catch (e) {
            }
        },
        //获得参数组, 类似request.getParameterValues()
        paramValues : function(o) { //  o: 参数名或者参数次序
            try {
                return (typeof(o) == 'number' ? data[o] : data[index[o]]);
            } catch (e) {}
        },
        //是否含有paramName参数
        hasParam : function(paramName) {
            return typeof(paramName) == 'string' ? typeof(index[paramName]) != 'undefined' : false;
        },
        // 获得参数Map ,类似request.getParameterMap()
        paramMap : function() {
            var map = {};
            try {
                for (var p in index) {  map[p] = data[index[p]];  }
            } catch (e) {}
            return map;
        }
    }
}();

Date.prototype.format = function(format)
{
    var o = {
        "M+" : this.getMonth()+1, //month
        "d+" : this.getDate(),    //day
        "h+" : this.getHours(),   //hour
        "m+" : this.getMinutes(), //minute
        "s+" : this.getSeconds(), //second
        "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
        "S" : this.getMilliseconds() //millisecond
    }
    if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
        (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)if(new RegExp("("+ k +")").test(format))
        format = format.replace(RegExp.$1,
            RegExp.$1.length==1 ? o[k] :
                ("00"+ o[k]).substr((""+ o[k]).length));
    return format;
}
